
class Event {
  private _eventRow: {
    [key: string]: ((...params: any[]) => any)[]
  } = {}
  on(event: string, fn: (...param: any[]) => any) {
    if (this._eventRow[event]) {
      this._eventRow[event].push(fn)
    } else {
      this._eventRow[event] = [fn]
    }
  }

  emit(event: string, ...args: any[]) {
    this._eventRow[event]?.forEach((fn) => fn.call(null, ...args))
  }
  off(event?: string, fn?: () => any) {
    // 没有参数 全部清空
    if (arguments.length === 0) {
      this._eventRow = {}
      return
    }

    // 有event 则对应的清空
    if (arguments.length === 1) {
      this._eventRow[event as string] = []
      return
    }
    let callbacks = this._eventRow[event as string]
    for (let i = 0; i < callbacks.length; i++) {
      if (callbacks[i] === fn) {
        callbacks.splice(i, 1)
        break
      }
    }
  }
}

export default new Event()
